package main

import (
	"encoding/base64"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"password/models"
	"strings"
)

const (
	CommandList   = "list"
	CommandAdd    = "add"
	CommandDelete = "delete"
	CommandUpdate = "update"
	FileName      = "password.txt"
)

func convertJson2Str(password *models.Password) string {
	data, err := json.Marshal(password)
	if err != nil {
		log.Printf(">> JSON格式化错误 %v", err)
		return ""
	}
	passJson := string(data)
	log.Printf(">> %v", passJson)
	encoded := base64.StdEncoding.EncodeToString(data)
	log.Printf(">> %v", encoded)
	encoded += ";"
	return encoded
}

func main() {
	log.Printf(">> 密码管理器启动中...")
	log.Printf(">> 开始检查运行参数...")
	args := os.Args
	if len(args) < 2 {
		log.Printf(">> 未输入任何命令,终止执行!")
		return
	}

	file, _ := os.Open(FileName)
	if file == nil {
		log.Printf(">> 密码存储文件不存在,准备初始化新建文件")
		file, _ = os.Create(FileName)
		log.Printf(">> 新建文件成功!")
	}
	defer file.Close()

	commandInput := args[1]
	switch commandInput {
	case CommandList:
		log.Printf("list")
		content, _ := ioutil.ReadAll(file)
		allStr := string(content)
		if allStr != "" {
			strArr := strings.Split(allStr, ";")
			if len(strArr) > 0 {
				for index, jsonStr := range strArr {
					decodeString, _ := base64.StdEncoding.DecodeString(jsonStr)
					log.Printf("序号: %v,json: %v", index, string(decodeString))
				}
			}
		}
	case CommandAdd:
		if len(args) < 3 {
			log.Printf("命令为[add]时候，必须输入用户名和密码")
			return
		}
		account := args[2]
		password := args[3]

		var remark = ""
		if len(args) > 4 {
			remark = args[4]
		}

		if account == "" || password == "" {
			log.Printf("用户名和密码不能为空")
		}

		pass := new(models.Password)
		pass.Account = account
		pass.Password = password
		pass, _ = pass.Create(remark)

		content, _ := ioutil.ReadAll(file)
		str := string(content)
		if str == "" {
			objStr := convertJson2Str(pass)
			newStr := []byte(objStr)
			err2 := ioutil.WriteFile(FileName, newStr, 0666)
			if err2 != nil {
				log.Printf(">> JSON格式化错误 %v", err2)
				return
			}
		} else {
			objStr := convertJson2Str(pass)
			str += "\n" + objStr
			newStr := []byte(str)
			err2 := ioutil.WriteFile(FileName, newStr, 0666)
			if err2 != nil {
				log.Printf(">> JSON格式化错误 %v", err2)
				return
			}
		}
	case CommandDelete:
		log.Printf("delete")
	case CommandUpdate:
		log.Printf("update")

	}
	//fmt.Println("命令行的参数有", len(os.Args))
	//// 遍历 os.Args 切片，就可以得到所有的命令行输入参数值
	//for i, v := range args {
	//	fmt.Printf("args[%v]=%v\n", i, v)
	//}
}
